// pages/home/mcar.js
const App = getApp()
import Kits from '../../utils/kits'

Page({
  data: {
    init: false,
    CustomBar: App.Global.CustomBar,

    clk: '',
    mch: '',

    begin: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    close: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    hdays: '',

    cars: []
  },
  onLoad(options) {
    this.setData({
      CustomBar: App.Global.CustomBar,
      clk: options.clkid,
      mch: options.mchid,
    })
    let now = new Date().addDays(1)
    let day = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 9, 0, 0, 0)
    this.doSetDates(day, day.addDays(2))
  },
  doLoadCars() {
    if (this.data.loadcar && !this.data.mch) {
      return
    }
    this.data.loadcar = true
    App.doPost({
      uri: '/app/base/biz/car/mch',
      body: {
        mid: this.data.mch,
        begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
        close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
      },
      fnSucc: resp => {
        resp.data.items.forEach(item => {
          item.price.pdpStr = Kits.fmtMoneyString(item.price.pdp)
          item.price.pmpStr = Kits.fmtMoneyString(item.price.pmp)
          item.price.mdpStr = Kits.fmtMoneyString(item.price.mdp)
          item.price.depositStr = Kits.fmtMoneyString(item.price.deposit)
          item.price.dispStr = Kits.fmtMoneyString(item.price.disp)

        })
        this.setData({
          init: true,
          cars: resp.data.items
        })
      },
      fnComp: () => {
        this.data.loadcar = false
      }
    })
  },
  // 设置日期
  doSetDates(beginTime, closeTime) {
    let begin = {
      value: beginTime.getTime(),
      year: beginTime.format('yyyy'),
      date: beginTime.format('MM月dd日'),
      time: beginTime.format('HH:mm'),
    }
    let close = {
      value: closeTime.getTime(),
      year: closeTime.format('yyyy'),
      date: closeTime.format('MM月dd日'),
      time: closeTime.format('HH:mm'),
    }
    this.setData({
      begin: begin,
      close: close,
      hdays: Kits.getDateMemo(beginTime, closeTime)
    })
    this.doLoadCars()
  },
  // 跳转选择日期界面
  toSelectDate() {
    wx.navigateTo({
      url: `/pages/order/calendar?carid=&begin=${this.data.begin.value}&close=${this.data.close.value}`,
      events: {
        enter: (e) => {
          this.doSetDates(new Date(e.begin), new Date(e.close))
        }
      }
    })
  }, // 去下单
  toCreateOrder(e) {
    let car = e.currentTarget.dataset.car
    wx.navigateTo({
      url: `/pages/order/create?clk=${this.data.clk}&carid=${car.id}&begin=${this.data.begin.value}&close=${this.data.close.value}&onsite=&onsite_area=&onsite_locs=&onsite_addr=`,
    })
  },
})